import React, { useState, useEffect } from 'react'
import { DndContext, PointerSensor, useSensor, useSensors } from '@dnd-kit/core'
import { restrictToVerticalAxis } from '@dnd-kit/modifiers'
import {
  arrayMove,
  SortableContext,
  useSortable,
  verticalListSortingStrategy
} from '@dnd-kit/sortable'
import { CSS } from '@dnd-kit/utilities'
import './index.modules.scss'
import { baseURL } from '@/http/request'
import { PlusOutlined, DeleteOutlined, EyeOutlined } from '@ant-design/icons'
import debounce from '@/components/js/throttle'
import {
  Space,
  Table,
  Button,
  Image,
  Modal,
  Card,
  message,
  Form,
  Upload,
  Input,
  Popconfirm,
  Pagination,
  Col,
  Row
} from 'antd'
import {
  shoppingListAdd,
  shoppingListDelete,
  shoppingListChange,
  shoppingList,
  shoppingListSrot
} from '@/http/api/shopping'
const { TextArea } = Input
let pageData2 = {
  page: 1,
  size: 10,
  total: 0,
  type: 1
}

const Row2 = (props) => {
  const {
    attributes,
    listeners,
    setNodeRef,
    transform,
    transition,
    isDragging
  } = useSortable({
    id: props['data-row-key']
  })
  const style = {
    ...props.style,
    transform: CSS.Translate.toString(transform),
    transition,
    cursor: 'move',
    ...(isDragging
      ? {
          position: 'relative',
          zIndex: 9999
        }
      : {})
  }
  return (
    <tr
      {...props}
      ref={setNodeRef}
      style={style}
      {...attributes}
      {...listeners}
    />
  )
}
let _id = ''
const App = React.forwardRef((props, ref) => {
  const [messageApi, contextHolder] = message.useMessage()
  useEffect(() => {
    getList()
  }, [])
  const handleChildMethod = () => {
    getList()
  }

  React.useImperativeHandle(ref, () => ({
    handleChildMethod
  }))
  const [dataSource2, setDataSource2] = useState([])
  const [isShowAdd2, serIsShowAdd2] = useState(false)
  const [form2] = Form.useForm()
  const [fileList, setFileList] = useState([])
  const [fileList2, setFileList2] = useState([])
  const [magnifyImg, setMagnifyImg] = useState('')
  const [isImgShow, setIsImgShow] = useState(false)
  const columns2 = [
    {
      title: '商品名称',
      dataIndex: 'name',
      align: 'center'
    },
    {
      title: '图片',
      dataIndex: 'img',
      align: 'center',
      render: (image) => {
        return (
          <Image
            width={60}
            height={60}
            src={image}
            fallback=""
          />
        )
      }
    },
    {
      title: '图片',
      dataIndex: 'introduceImg',
      align: 'center',
      render: (introduceImg) => {
        return (
          <Image
            width={60}
            height={60}
            src={JSON.parse(introduceImg)[0]}
            fallback=""
          />
        )
      }
    },
    {
      title: '商品标题',
      dataIndex: 'title',
      align: 'center'
    },
    {
      title: '价格 ',
      dataIndex: 'price',
      align: 'center'
    },
    {
      title: '操作',
      key: 'action',
      align: 'center',
      render: (data) => (
        <Space size="middle">
          <Button
            type="primary"
            onClick={() => {
              showModalAdd(data)
            }}
          >
            编辑
          </Button>
          <Popconfirm
            title="删除"
            description="确定删除吗?"
            placement="top"
            onConfirm={() => {
              DeleteFn(data)
            }}
            onCancel={() => {
              message.error('取消删除')
            }}
            okText="是"
            cancelText="不"
          >
            <Button type="primary" danger>
              删除
            </Button>
          </Popconfirm>
        </Space>
      )
    }
  ]
  const sensors2 = useSensors(
    useSensor(PointerSensor, {
      activationConstraint: {
        distance: 1
      }
    })
  )
  // 获取列表
  const getList = async () => {
    pageData2.appid = localStorage.getItem('appid')
    const res = await shoppingList({ ...pageData2 })
    setDataSource2(
      res.data.res.map((item) => {
        return {
          ...item,
          key: item._id
        }
      })
    )
    pageData2.total = res.data.total
  }
  const onDragEnd = ({ active, over }) => {
    let dataList = []
    if (active.id !== over?.id) {
      setDataSource2((prev) => {
        const activeIndex = prev.findIndex((i) => i.key === active.id)
        const overIndex = prev.findIndex((i) => i.key === over?.id)
        dataList = arrayMove(prev, activeIndex, overIndex)
        return arrayMove(prev, activeIndex, overIndex)
      })
    }
    debounce(() => {
      sortFn(dataList)
    }, 100)
  }
  const sortFn = async (data) => {
    let ids = data.map((item) => {
      return item._id
    })
    let sort = dataSource2.map((item) => {
      return item.sort
    })
    await shoppingListSrot({ ids, sort })
  }
  const showModalAdd = (value) => {
    if (value._id) {
      let data = JSON.parse(JSON.stringify(value))
      form2.setFieldsValue(data)
      _id = value._id
    }
    setFileList([value.img])
    setFileList2(JSON.parse(value.introduceImg))
    serIsShowAdd2(true)
  }
  // 添加
  const onFinish = async (data) => {
    try {
      data.img = fileList[0]
      data.introduceImg = fileList2
      delete data.imageurl
      data.appid = localStorage.getItem('appid')
      let res = ''
      if (_id) {
        data._id = _id
        res = await shoppingListChange(data)
      } else {
        data.type = 1
        res = await shoppingListAdd(data)
      }
      form2.resetFields()
      messageApi.success(res.data.message)
      serIsShowAdd2(false)
      setFileList([])
      setFileList2([])
      props.getList()
    } catch (error) {
      messageApi.error('失败')
    }
    _id = ''
  }
  const pageChangeFn = (page, pageSize) => {
    pageData2.page = page
    pageData2.size = pageSize
    getList()
  }
  // 删除
  const DeleteFn = async (data) => {
    const res = await shoppingListDelete({ id: data._id })
    messageApi.success(res.data.message)
    props.getList()
  }
  // 删除照片
  const deleteImgFn = (index) => {
    let imgData = [...fileList]
    imgData.splice(index, 1)
    setFileList(imgData)
  }
  const imgageChangeFn = (data) => {
    if (data.file.status == 'done') {
      setFileList([
        ...fileList,
        ...data.fileList.map((item) => {
          return item.response.image_url
        })
      ])
    }
  }
  const imgageChangeFn2 = (data) => {
    if (data.file.status == 'done') {
      setFileList2([
        ...fileList2,
        ...data.fileList.map((item) => {
          return item.response.image_url
        })
      ])
    }
  }
  return (
    <div>
      {/* 所有商品 */}
      <Card>
        <div className="headerButton">
          <div className="title">人气爆棚商品</div>
          <Button
            type="primary"
            onClick={() => {
              serIsShowAdd2(true)
            }}
          >
            添加内容
          </Button>
        </div>
        <DndContext
          sensors={sensors2}
          modifiers={[restrictToVerticalAxis]}
          onDragEnd={onDragEnd}
        >
          <SortableContext
            items={dataSource2.map((i) => i.key)}
            strategy={verticalListSortingStrategy}
          >
            <Table
              pagination={false}
              bordered
              components={{
                body: {
                  row: Row2
                }
              }}
              rowKey="key"
              columns={columns2}
              dataSource={dataSource2}
            />
          </SortableContext>
        </DndContext>
        <div className="Pagin">
          <Pagination
            onChange={pageChangeFn}
            defaultCurrent={pageData2.page}
            total={pageData2.total}
          />
        </div>
      </Card>
      <div>
        <Modal
          title="添加"
          footer={[]}
          onCancel={() => {
            serIsShowAdd2(false)
            form2.resetFields()
            setFileList([])
            setFileList2([])
          }}
          open={isShowAdd2}
        >
          <Form
            labelCol={{
              span: 5
            }}
            wrapperCol={{
              span: 14
            }}
            layout="horizontal"
            style={{
              maxWidth: 800
            }}
            form={form2}
            onFinish={onFinish}
          >
            <Form.Item
              label="商品名称"
              name="name"
              rules={[
                {
                  required: true,
                  message: '请输入名称'
                }
              ]}
            >
              <Input />
            </Form.Item>
            <Form.Item
              label="商品图片"
              name="img"
              rules={[
                {
                  required: true,
                  message: '请选择图片'
                }
              ]}
            >
              <div>
                <div className="upImgBox align_center">
                  {fileList.length == 0 ? (
                    <Upload
                      maxCount={1}
                      action={baseURL + 'api/uploadAvatar'}
                      listType="picture-card"
                      accept=".png,.jpg"
                      onChange={imgageChangeFn}
                    >
                      <button
                        style={{
                          border: 0,
                          background: 'none'
                        }}
                        type="button"
                      >
                        <PlusOutlined />
                        <div
                          style={{
                            marginTop: 8
                          }}
                        ></div>
                      </button>
                    </Upload>
                  ) : (
                    fileList.map((item, index) => {
                      return (
                        <div key={index} className="imgBox center">
                          <img
                            style={{ width: '100%', height: '100%' }}
                            src={item}
                            alt=""
                          />
                          <div
                            className="mask center"
                            style={{ justifyContent: 'space-evenly' }}
                          >
                            <DeleteOutlined
                              onClick={() => {
                                deleteImgFn(index)
                              }}
                              style={{ fontSize: 20, color: '#FFFFFF' }}
                            />
                            <EyeOutlined
                              onClick={() => {
                                setMagnifyImg(item)
                                setIsImgShow(true)
                              }}
                              style={{ fontSize: 20, color: '#FFFFFF' }}
                            />
                          </div>
                        </div>
                      )
                    })
                  )}
                </div>
              </div>
            </Form.Item>
            <Form.Item
              label="商品介绍图"
              name="introduceImg"
              rules={[
                {
                  required: true,
                  message: '请选择图片'
                }
              ]}
            >
              <div>
                <div className="upImgBox align_center">
                  <Row>
                    {fileList2.map((item, index) => {
                      return (
                        <Col span={12} key={index}>
                          <div className="imgBox center">
                            <img
                              style={{ width: '100%', height: '100%' }}
                              src={item}
                              alt=""
                            />
                            <div
                              className="mask center"
                              style={{ justifyContent: 'space-evenly' }}
                            >
                              <DeleteOutlined
                                onClick={() => {
                                  deleteImgFn(index)
                                }}
                                style={{ fontSize: 20, color: '#FFFFFF' }}
                              />
                              <EyeOutlined
                                onClick={() => {
                                  setMagnifyImg(item)
                                  setIsImgShow(true)
                                }}
                                style={{ fontSize: 20, color: '#FFFFFF' }}
                              />
                            </div>
                          </div>
                        </Col>
                      )
                    })}
                  </Row>
                  <Upload
                    maxCount={1}
                    action={baseURL + 'api/uploadAvatar'}
                    listType="picture-card"
                    accept=".png,.jpg"
                    onChange={imgageChangeFn2}
                    showUploadList={false}
                  >
                    <button
                      style={{
                        border: 0,
                        background: 'none'
                      }}
                      type="button"
                    >
                      <PlusOutlined />
                      <div
                        style={{
                          marginTop: 8
                        }}
                      ></div>
                    </button>
                  </Upload>
                </div>
              </div>
            </Form.Item>
            <Form.Item
              label="图片标题"
              name="title"
              rules={[
                {
                  required: true,
                  message: '请输入备注'
                }
              ]}
            >
              <Input />
            </Form.Item>
            <Form.Item
              label="价格"
              name="price"
              rules={[
                {
                  required: true,
                  message: '请输入价格'
                }
              ]}
            >
              <Input />
            </Form.Item>
            <Form.Item
              label="单位"
              name="unit"
              rules={[
                {
                  required: true,
                  message: '请输入单位'
                }
              ]}
            >
              <Input />
            </Form.Item>
            <Form.Item
              label="介绍"
              name="introduce"
              rules={[
                {
                  required: true,
                  message: '请输入介绍'
                }
              ]}
            >
              <TextArea rows={4} placeholder="请输入介绍" />
            </Form.Item>
            <Form.Item
              wrapperCol={{
                offset: 6,
                span: 16
              }}
            >
              <Button type="primary" htmlType="submit">
                确定
              </Button>
              <Button
                style={{ marginLeft: '10px' }}
                type="primary"
                onClick={() => {
                  form2.resetFields()
                  serIsShowAdd2(false)
                }}
              >
                取消
              </Button>
            </Form.Item>
          </Form>
        </Modal>
      </div>
      {/* 图片放大效果 */}
      <Modal
        open={isImgShow}
        footer={[]}
        onCancel={() => {
          setIsImgShow(false)
        }}
        closable={false}
      >
        <div>
          <img className="ImgShow" src={magnifyImg} alt="" srcset="" />
        </div>
      </Modal>
      {contextHolder}
    </div>
  )
})
export default App
